<!-- 客户端管理 -->
<template>
  <div class="process-container">
    <div class="table__wrapper">
      <transition :enter-active-class="this.animate.searchAnimate.enter" :leave-active-class="this.animate.searchAnimate.leave">
        <div class="search" v-show="showSearch">
          <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" label-width="100px">
            <el-form-item label="客户端key" prop="clientKey">
              <el-input v-model="queryParams.clientKey" placeholder="请输入客户端key" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户端秘钥" prop="clientSecret">
              <el-input v-model="queryParams.clientSecret" placeholder="请输入客户端秘钥" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable>
                <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </transition>
      <div class="table-operates">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd" :disabled="total===maxClient" v-hasPermi="['system:client:add']">新增 <span v-if="maxClient!=-1">({{total}}/{{maxClient}})</span></el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" size="mini" icon="el-icon-edit-outline" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:client:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:client:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" size="mini" icon="el-icon-download" @click="handleExport" v-hasPermi="['system:client:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>

      <el-table v-loading="loading" :data="clientList" height="100%" class="common-table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="客户端名称" align="center" prop="clientName">
          <template #default="{row}">
            {{row.clientName || '--'}}
          </template>
        </el-table-column>
        <el-table-column label="客户端id" align="center" prop="clientId" />
        <el-table-column label="客户端key" align="center" prop="clientKey" />
        <el-table-column label="客户端秘钥" align="center" prop="clientSecret" />
        <el-table-column label="授权类型" align="center">
          <template #default="scope">
            <dict-tag :options="dict.type.sys_grant_type" :value="scope.row.grantTypeList" />
          </template>
        </el-table-column>
        <el-table-column label="设备类型" align="center">
          <template #default="scope">
            <dict-tag :options="dict.type.sys_device_type" :value="scope.row.deviceType" />
          </template>
        </el-table-column>
        <el-table-column label="Token活跃超时时间" align="center" prop="activeTimeout" />
        <el-table-column label="Token固定超时时间" align="center" prop="timeout" />
        <el-table-column label="状态" align="center" key="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="接口设置" placement="top">
              <el-button type="text" icon="el-icon-setting" @click="handleSettings(scope.row)" v-hasPermi="['system:client:settings']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button type="text" icon="el-icon-edit-outline" @click="handleUpdate(scope.row)" v-hasPermi="['system:client:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:client:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 添加或修改客户端管理对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="500px" append-to-body>
      <el-form ref="clientFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户端名称" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入客户端名称" />
        </el-form-item>
        <el-form-item label="客户端key" prop="clientKey">
          <el-input v-model="form.clientKey" :disabled="form.id != null" placeholder="请输入客户端key" />
        </el-form-item>
        <el-form-item label="客户端秘钥" prop="clientSecret">
          <el-input v-model="form.clientSecret" :disabled="form.id != null" placeholder="请输入客户端秘钥" style="width:257px; margin-right:5px;"></el-input>
          <el-button type="primary" :disabled="form.id != null" @click="generateSecret">生成秘钥</el-button>
        </el-form-item>
        <el-form-item label="授权类型" prop="grantTypeList">
          <el-select v-model="form.grantTypeList" multiple placeholder="请输入授权类型">
            <el-option v-for="dict in dict.type.sys_grant_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请输入设备类型">
            <el-option v-for="dict in dict.type.sys_device_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="activeTimeout" label-width="auto">
          <template #label>
            <span>
              <el-tooltip content="指定时间无操作则过期（单位：秒），默认30分钟（1800秒）" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              Token活跃超时时间
            </span>
          </template>
          <el-input v-model="form.activeTimeout" placeholder="请输入Token活跃超时时间" />
        </el-form-item>
        <el-form-item prop="timeout" label-width="auto">
          <template #label>
            <span>
              <el-tooltip content="指定时间必定过期（单位：秒），默认七天（604800秒）" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              Token固定超时时间
            </span>
          </template>
          <el-input v-model="form.timeout" placeholder="请输入Token固定超时时间" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer :title="settingTitle" :visible.sync="showSettings" size="70%" :before-close="handleCloseSettings">
      <TenantSettings v-model="curClinet" v-if="showSettings" />
    </el-drawer>
  </div>
</template>

<script>
import {
  listClient,
  getClient,
  delClient,
  addClient,
  updateClient,
  changeStatus,
} from '@/api/system/client'
import TenantSettings from './settings.vue'
import { v4 as uuidv4 } from 'uuid'
const initFormData = {
  id: undefined,
  clientName: undefined,
  clientId: undefined,
  clientKey: undefined,
  clientSecret: undefined,
  grantTypeList: undefined,
  deviceType: undefined,
  activeTimeout: undefined,
  timeout: undefined,
  status: undefined,
}
export default {
  name: 'Client',
  dicts: ['sys_normal_disable', 'sys_grant_type', 'sys_device_type'],
  //import引入的组件需要注入到对象中才能使用
  components: { TenantSettings },
  data() {
    //这里存放数据
    return {
      showSettings: false,
      settingTitle: '未定义 · 接口设置',
      curClinet: null,
      clientList: [],
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      maxClient: -1,
      dialog: {
        visible: false,
        title: '',
      },
      form: { ...initFormData },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientId: undefined,
        clientKey: undefined,
        clientSecret: undefined,
        grantType: undefined,
        deviceType: undefined,
        activeTimeout: undefined,
        timeout: undefined,
        status: undefined,
      },
      rules: {
        id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
        clientName: [
          { required: true, message: '客户端名称不能为空', trigger: 'blur' },
        ],
        clientId: [
          { required: true, message: '客户端id不能为空', trigger: 'blur' },
        ],
        clientKey: [
          { required: true, message: '客户端key不能为空', trigger: 'blur' },
        ],
        clientSecret: [
          { required: true, message: '客户端秘钥不能为空', trigger: 'blur' },
        ],
        grantTypeList: [
          { required: true, message: '授权类型不能为空', trigger: 'change' },
        ],
        deviceType: [
          { required: true, message: '设备类型不能为空', trigger: 'change' },
        ],
      },
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    console.log(uuidv4())
    this.getList()
  },
  methods: {
    generateSecret() {
      this.form.clientSecret = uuidv4()
    },
    /** 查询客户端管理列表 */
    async getList() {
      this.loading = true
      const res = await listClient(this.queryParams)
      this.clientList = res.rows
      this.total = res.total
      this.maxClient = res.maxClient
      this.loading = false
    },

    /** 取消按钮 */
    cancel() {
      this.reset()
      this.dialog.visible = false
    },

    /** 表单重置 */
    reset() {
      this.form = { ...initFormData }
      this.$refs.clientFormRef && this.$refs.clientFormRef.resetFields()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryFormRef.resetFields()
      this.handleQuery()
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.dialog.visible = true
      this.dialog.title = '添加客户端管理'
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      const _id = row?.id || this.ids[0]
      const res = await getClient(_id)
      Object.assign(this.form, res.data)
      this.dialog.visible = true
      this.dialog.title = '修改客户端管理'
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.clientFormRef.validate(async (valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id) {
            await updateClient(this.form).finally(
              () => (this.buttonLoading = false)
            )
          } else {
            await addClient(this.form).finally(
              () => (this.buttonLoading = false)
            )
          }
          this.$modal.msgSuccess('修改成功')
          this.dialog.visible = false
          await this.getList()
        }
      })
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      const _ids = row?.id || this.ids
      await this.$modal
        .confirm('是否确认删除客户端管理编号为"' + _ids + '"的数据项？')
        .finally(() => (this.loading = false))
      await delClient(_ids)
      this.$modal.msgSuccess('删除成功')
      await this.getList()
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/client/export',
        {
          ...this.queryParams,
        },
        `client_${new Date().getTime()}.xlsx`
      )
    },

    /** 状态修改  */
    async handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      try {
        await this.$modal.confirm('确认要"' + text + '"吗?')
        await changeStatus(row.id, row.status)
        this.$modal.msgSuccess(text + '成功')
      } catch (err) {
        row.status = row.status === '0' ? '1' : '0'
      }
    },
    /** 接口设置 */
    handleSettings(row) {
      this.curClinet = { ...row }
      this.settingTitle = `${this.curClinet.clientName} · 接口设置`
      this.showSettings = true
    },
    handleCloseSettings(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-drawer__header {
  margin-bottom: 20px;
}
</style>